package com.easemob.chatuidemo.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.animation.AlphaAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.chatuidemo.DemoHXSDKHelper;
import com.wee.aircoach_user.MyApplication;
import com.wee.aircoach_user.R;
import com.easemob.exceptions.EaseMobException;

/**
 * 开屏页
 *
 */
public class SplashActivity extends BaseActivity {
	private RelativeLayout rootLayout;
	private TextView versionText;
	
	private static final int sleepTime = 2000;

	@Override
	protected void onCreate(Bundle arg0) {
		setContentView(R.layout.activity_splash);
		super.onCreate(arg0);

		rootLayout = (RelativeLayout) findViewById(R.id.splash_root);
		versionText = (TextView) findViewById(R.id.tv_version);

		versionText.setText(getVersion());
		AlphaAnimation animation = new AlphaAnimation(0.3f, 1.0f);
		animation.setDuration(1500);
		rootLayout.startAnimation(animation);
	}

	@Override
	protected void onStart() {
		super.onStart();

//		new Thread(new Runnable() {
//			public void run() {
//				if (DemoHXSDKHelper.getInstance().isLogined()) {
//					// ** 免登陆情况 加载所有本地群和会话
//					//不是必须的，不加sdk也会自动异步去加载(不会重复加载)；
//					//加上的话保证进了主页面会话和群组都已经load完毕
//					long start = System.currentTimeMillis();
//					EMGroupManager.getInstance().loadAllGroups();
//					EMChatManager.getInstance().loadAllConversations();
//					long costTime = System.currentTimeMillis() - start;
//					//等待sleeptime时长
//					if (sleepTime - costTime > 0) {
//						try {
//							Thread.sleep(sleepTime - costTime);
//						} catch (InterruptedException e) {
//							e.printStackTrace();
//						}
//					}
//					//进入主页面
//                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
//                    finish();
//				}else {
//					try {
//						Thread.sleep(sleepTime);
//					} catch (InterruptedException e) {
//					}
//					startActivity(new Intent(SplashActivity.this, LoginActivity.class));
//					finish();
//				}
//			}
//		}).start();
		register();
	}
	
	/**
	 * 获取当前应用程序的版本号
	 */
	private String getVersion() {
		String st = getResources().getString(R.string.Version_number_is_wrong);
		PackageManager pm = getPackageManager();
		try {
			PackageInfo packinfo = pm.getPackageInfo(getPackageName(), 0);
			String version = packinfo.versionName;
			return version;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return st;
		}
	}
	
	private void login(){
	    EMChatManager.getInstance().login("slider0", "123456", new EMCallBack() {
            
            @Override
            public void onSuccess() {
                //进入主页面
                startActivity(new Intent(SplashActivity.this, MainActivity_hx.class));
                finish();
            }
            
            @Override
            public void onProgress(int arg0, String arg1) {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void onError(int arg0, String arg1) {
                // TODO Auto-generated method stub
                
            }
        });
	}
	
	private void register(){
	    if (DemoHXSDKHelper.getInstance().isLogined()) {
	      //进入主页面
            startActivity(new Intent(SplashActivity.this, MainActivity_hx.class));
            finish();
	        return;
	    }
	    final ProgressDialog pd = new ProgressDialog(this);
        pd.setMessage(getResources().getString(R.string.Is_the_registered));
        pd.show();

        new Thread(new Runnable() {
            public void run() {
                try {
                    // 调用sdk注册方法
                    final String username = "slider0";
                    String pwd = "123456";
                    EMChatManager.getInstance().createAccountOnServer("slider0", "123456");
                    EMChatManager.getInstance().createAccountOnServer("slider1", "123456");
                    runOnUiThread(new Runnable() {
                        public void run() {
                            if (!SplashActivity.this.isFinishing())
                                pd.dismiss();
                            // 保存用户名
                            MyApplication.getInstance().setUserName(username);
                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registered_successfully), Toast.LENGTH_SHORT).show();
                            login();
                            //finish();
                        }
                    });
                } catch (final EaseMobException e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            if (!SplashActivity.this.isFinishing())
                                pd.dismiss();
                            int errorCode=e.getErrorCode();
                            if(errorCode==EMError.NONETWORK_ERROR){
                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
                            }else if(errorCode == EMError.USER_ALREADY_EXISTS){
                                login();
                                //Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
                            }else if(errorCode == EMError.UNAUTHORIZED){
                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.registration_failed_without_permission), Toast.LENGTH_SHORT).show();
                            }else if(errorCode == EMError.ILLEGAL_USER_NAME){
                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name),Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registration_failed) + e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }
        }).start();
	}
}
